import 'dart:developer';

import 'package:get/get.dart';
import 'package:im_base/public/components/layout_widgets.dart';
import 'package:im_base/public/ext/im_base_controller.dart';
import 'package:im_base/public/global/im_keys.dart';
import 'package:im_base/public/service/tim_service.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_manager.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_conversation.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_friend_info.dart';

import '../../../../im_base.dart';
import 'state.dart';

class ConversationLogic extends IMBaseController {
  late V2TIMManager _v2timManager;
  final state = ConversationState();

  @override
  void onInit() {
    _v2timManager = TimService.instance.v2timManager!;
    super.onInit();
  }

  @override
  void onReady() {
    _watchConversation();
    _watchDelete();
    _watchFriendChange();
    super.onReady();
    getConversation();
  }

  @override
  void onClose() {
    super.onClose();
  }

  @override
  void refresh() {
    state.nextSeq = '0';
    super.refresh();
  }

  ///加载更多,获取最后一条消息的标识
  void loadMore() {
    state.nextSeq = state
        .conversationList[state.conversationList.length - 1]!.lastMessage!.seq!;
    getConversation();
  }

  ///拉取历史会话列表
  void getConversation() async {
    final conversation = await _v2timManager
        .getConversationManager()
        .getConversationList(nextSeq: state.nextSeq, count: state.pageSize);
    if (conversation.code == 0) {
      if (state.nextSeq == '0') {
        try {
          state.hasMore = (conversation.data!.conversationList != null &&
              conversation.data!.conversationList!.length >= state.pageSize);
          if (conversation.data!.conversationList == null ||
              conversation.data!.conversationList!.isEmpty) {
            state.loadingStatus = LoadStatus.EMPTY;
            update();
          } else {
            conversation.data!.conversationList!.removeWhere((element) {
              return element!.userID == "admin" || element.lastMessage == null;
            });
            state.loadingStatus = LoadStatus.FINISHED;
            state.conversationList.addAll(conversation.data!.conversationList!);
            await sortConversation();
          }
        } catch (e) {
          log("getConversation---$e");
        }
      } else {
        state.conversationList.addAll(conversation.data!.conversationList!);
        state.loadingStatus = LoadStatus.FINISHED;
        await sortConversation();
      }
    } else {
      state.loadingStatus = LoadStatus.FINISHED;
      update();
    }
  }

  ///根据时间进行会话排序
  Future<void> sortConversation() async {
    state.conversationList.removeWhere((element) {
      return element!.userID == "admin" || element.lastMessage == null;
    });
    state.conversationList.sort((left, right) =>
        (right!.lastMessage?.timestamp ?? 0)
            .compareTo(left!.lastMessage?.timestamp ?? 0));
    state.loadingStatus = LoadStatus.FINISHED;
    update();
  }

  ///监听会话列表变动
  void _watchConversation() {
    addKeyListener(IMKeys.conversationList, (conversation) {
      updateConversation(conversation);
    });

    addKeyListener(IMKeys.newConversation, (conversation) {
      state.conversationList.addAll(conversation);
      sortConversation();
    });
  }

  ///如果当前没有会话,或者是新会话不在会话列表中,则直接添加
  ///如果已在当前会话列表中,则比对会话id,更新该会话
  void updateConversation(List<V2TimConversation> list) async {
    if (state.conversationList.isEmpty) {
      state.conversationList.addAll(list);
    } else {
      state.loadingStatus = LoadStatus.FINISHED;
      list.forEach((element) {
        final conID = element.conversationID;
        state.conversationList.removeWhere((e) => e!.conversationID == conID);
        state.conversationList.add(element);
      });
    }
    await sortConversation();
  }

  ///根据会话id删除会话
  void deleteConversation(String conID) async {
    await _v2timManager
        .getConversationManager()
        .deleteConversation(conversationID: conID)
        .then((value) {
      if (value.code == 0) {
        state.conversationList
            .removeWhere((element) => element!.conversationID == conID);
        update();
      } else {
        showToast('删除失败:[${value.code}]:${value.desc}');
      }
    });
  }

  void _watchDelete() {
    addKeyListener(IMKeys.deleteConversation, (p0) {
      var con =
          state.conversationList.where((element) => element?.groupID == p0);
      if (con.isNotEmpty) {
        deleteConversation(con.first!.conversationID);
      }
    });
  }

  void  _watchFriendChange(){
    addKeyListener(IMKeys.friendInfoChange, (value) {
      log('onFriendInfoChanged-----${value.length}');
      if(value is List<V2TimFriendInfo>){
        value.forEach((info) {
          state.conversationList.where((element) => element?.userID==info.userID).first?.showName=info.friendRemark??'';
        });
        update();
      }
    });
  }
}
